import { CustomForm } from "@/components/ProForm/interface";
import dayjs from "dayjs";

export const useForm = () => {
  const addForm = reactive<CustomForm>({
    save: () => null,
    form: {
      price: "",
      amount: "",
      date: "",
      remark: "",
      type: "",
      type2: "",
      userId: ""
    },
    options: [
      {
        hide: false,
        label: "基础信息",
        type: "title"
      },
      {
        type: "date_custom",
        hide: false,
        label: "日期",
        prop: "date",
        defaultValue: dayjs().format("YYYY-MM-DD"),
        children: [],
        attrs: {
          type: "date"
        },
        rules: [
          {
            required: true,
            errorMessage: "日期"
          }
        ]
      },
      {
        type: "select",
        hide: false,
        label: "购买用户",
        prop: "userId",
        children: [],
        changeMethod: form => {
          getFindPositionsByUserId();
          getMoney();
          form.quantity = "";
        },
        rules: [
          {
            required: true,
            errorMessage: "购买用户"
          }
        ]
      },
      {
        type: "input",
        hide: false,
        label: "剩余金额",
        prop: "money",
        attrs: {
          disabled: true
        },
        rules: [
          {
            required: true,
            errorMessage: "剩余金额"
          }
        ]
      },
      {
        type: "input",
        hide: false,
        label: "持仓金额",
        prop: "positionAmount",
        attrs: {
          disabled: true
        },
        rules: [
          {
            required: true,
            errorMessage: "持仓金额"
          }
        ]
      },
      {
        type: "select",
        hide: false,
        label: "交易情况",
        prop: "type",
        defaultValue: 1,
        children: [],
        rules: [
          {
            required: true,
            errorMessage: "交易情况"
          }
        ]
      },
      {
        type: "select",
        hide: false,
        label: "交易类型",
        prop: "type2",
        children: [
          {
            text: "买入",
            value: "buy"
          },
          {
            text: "卖出",
            value: "sell"
          }
        ],
        rules: [
          {
            required: true,
            errorMessage: "交易类型"
          }
        ],
        changeMethod: () => {
          setTransactionAmount();
          const flag = addForm.form.type2 !== "buy";
          console.log(flag, "flag");

          changeFormItemStatus(addForm, ["dm"], flag, "hide");
          changeFormItemStatus(addForm, ["_dm"], !flag, "hide");
        }
      },
      {
        type: "input",
        label: "股票代码",
        hide: true,
        prop: "dm",
        attrs: {
          type: "number"
        },
        rules: [
          {
            required: true,
            errorMessage: "股票代码"
          }
        ]
      },
      {
        type: "select",
        label: "股票代码",
        hide: true,
        prop: "_dm",
        attrs: {},
        children: [],
        changeMethod: () => {
          const { quantity } = userInfo.positionsOp.find(item => item.dm === addForm.form._dm) || {};
          addForm.form.quantity = quantity;
          getMoney();
        },
        rules: [
          {
            required: true,
            errorMessage: "股票代码"
          }
        ]
      },
      {
        type: "input",
        label: "数量",
        hide: false,
        prop: "quantity",
        attrs: {
          type: "number"
        },
        rules: [
          {
            required: true,
            errorMessage: "数量"
          }
        ],
        inputMethod: () => setTransactionAmount()
      },
      {
        type: "input",
        label: "价格",
        hide: false,
        prop: "price",
        attrs: {
          type: "digit",
          placeholder: "价格(元)"
        },
        correctionParams: {
          digit: 2
        },
        rules: [
          {
            required: true,
            errorMessage: "价格"
          }
        ],
        inputMethod: () => setTransactionAmount()
      },
      {
        type: "input",
        label: "交易金额",
        hide: false,
        prop: "amount",
        attrs: {
          type: "digit",
          placeholder: "交易金额(元)",
          disabled: true
        },
        rules: [
          {
            required: true,
            errorMessage: "交易金额"
          }
        ]
      },
      {
        type: "input",
        label: "交易费用",
        hide: false,
        prop: "cost",
        attrs: {
          type: "digit",
          placeholder: "交易费用(元)",
          disabled: true
        },
        rules: [
          {
            required: true,
            errorMessage: "交易金额"
          }
        ]
      },
      {
        type: "input",
        label: "备注",
        hide: false,
        prop: "remark",
        attrs: {
          disabled: false
        }
      }
    ]
  });

  let userInfo = {
    money: 0,
    id: 0,
    userOp: [],
    // 持仓列表
    positionsOp: []
  };

  /**
   * @description: 获取所有用户
   * @return {*}
   */
  const getAllUser = async () => {
    const data: any = await userFindAllUser();
    userInfo.userOp = data;

    for (let item of addForm.options) {
      if (item.prop === "userId") {
        item.children = data.map(item => {
          return {
            text: item.uname,
            value: item.id
          };
        });
      }
    }
  };

  const getMoney = () => {
    const { money } = userInfo.userOp.find(item => item.id === addForm.form.userId);
    addForm.form.money = money;
  };

  /**
   * 获取用户持仓情况
   */
  const getFindPositionsByUserId = async () => {
    const data: any = await positionsFindPositionsByUserId({ userId: addForm.form.userId });
    addForm.form.positionAmount = data.buyPrice;
    userInfo.positionsOp = data.list;
    for (let item of addForm.options) {
      if (item.prop === "_dm") {
        item.children = changeArrField(data.list, "mc", "dm");
        return;
      }
    }
  };

  /**
   * @description: 设置交易金额
   * @return {*}
   */
  const setTransactionAmount = () => {
    nextTick(() => {
      const { price, quantity, type2 } = addForm.form;
      let cost = 0;
      let amount = 0;
      if (price && quantity) {
        amount = Math.round(price * quantity * 100) / 100;
        console.log(amount, "amount");

        // 买入费用: 总金额 * 0.0005
        if (type2 === "buy") {
          cost = Math.round(amount * 0.0005 * 100) / 100;
          console.log(cost, "cost");

          if (cost < 5) {
            cost = 5;
          }
        } else {
          // 卖出费用: 总金额 * 0.001
          cost = Math.round(amount * 0.001 * 100) / 100;
        }
        addForm.form.amount = amount;
        addForm.form.cost = cost;
      }
    });
  };

  const submitForm = async form => {
    form.dm = form.dm || form._dm;
    form.quantity = parseFloat(form.quantity);
    form.price = parseFloat(form.price);
    await transactionsAddTransactions(form);
    useGlobalStore().setMessage();
    clearForm();
  };

  const clearForm = () => {
    Object.keys(addForm.form).forEach(key => {
      if (key !== "date") {
        addForm.form[key] = "";
      }
    });

    // 重新获取用户得到新的金额
    getAllUser();
  };

  return {
    addForm,
    submitForm,
    getFindPositionsByUserId,
    getMoney,
    getAllUser
  };
};
